package com.bincloud.vue.admin.web.component;

import com.bincloud.vue.admin.common.util.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TraceIdInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID = "traceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 日志新增 traceId
        log.debug("preHandle running ...");
        if (MDC.get(TRACE_ID) == null || "".equals(MDC.get(TRACE_ID))) {
            MDC.put(TRACE_ID, IdUtils.simpleUUID());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // 防止内存泄露
        MDC.remove(TRACE_ID);
    }
}
